package com.zzyl.common.utils;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.canvas.parser.PdfTextExtractor;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class PdfReaderUtil {
    /**
     * 从InputStream读取PDF内容并返回字符串
     *
     * @param inputStream PDF输入流
     * @return PDF内容字符串
     * @throws IOException 如果读取失败
     */
    public static String readPdfFromStream(InputStream inputStream) throws IOException {
        try (PdfReader reader = new PdfReader(inputStream);
             PdfDocument document = new PdfDocument(reader)) {

            StringBuilder textBuilder = new StringBuilder();
            for (int i = 1; i <= document.getNumberOfPages(); i++) {
                String pageText = PdfTextExtractor.getTextFromPage(document.getPage(i));
                textBuilder.append(pageText);

                // 可选：添加分页符（保留页面结构）
                if (i < document.getNumberOfPages()) {
                    textBuilder.append("\n\n--- 第 ").append(i).append(" 页结束 ---\n\n");
                }
            }
            return textBuilder.toString();
        }
    }
}